/**
 * Load and initialize the Facebook SDK.
 * 
 * Provides FB.api('/some-user', function(user) { }); User 'me' acesses the
 * current user
 */
window.fbAsyncInit = function() {
	FB.init({
		appId : '257615834280234',
		status : true,
		cookie : true,
		xfbml : true
	});

	FB.Event.subscribe('auth.login', function(response) {
		window.location.reload();
	});

	window.logout = function() {
		FB.getLoginStatus(function(response) {
			if (response.status == 'connected') {
				FB.logout(function(r) {
					window.location.href = '/logout';
				});
			} else {
				window.location.href = '/logout';
			}
		});
	};

	window.checkin = function(place, message) {
		var myLogin = function() {
			FB.login(function(loginR) {
				// var placeId = '165895456757483'; // 30 Dean St. 'place' ID
				var uid = loginR.session.uid;

				FB.api('/' + place, function(placeR) {
					// var str = '';
					// for ( var l in placeR.location) {
					// str += l + ': ' + placeR.location[l] + '\n';
					// }
					// console.log('Place' + str);
					FB.api('/' + uid + '/checkins', 'POST', {
						place : place,
						message : message,
						coordinates : placeR.location
					}, function(postR) {
						var str = '';
						for ( var l in postR.error) {
							str += l + ': ' + postR.error[l] + '\n';
						}
						console.log('Check In: ' + str);
					});
				});
			}, {
				scope : "email,publish_checkins"
			});
		};

		FB.getLoginStatus(function(response) {
			if (response.status == 'connected') {
				FB.logout(function(logoutR) {
					myLogin();
				});
			} else {
				myLogin();
			}
		});
	};
};

// Asynchronously fetch the Facebook SDK
(function(d) {
	var js, id = 'facebook-jssdk';
	if (d.getElementById(id)) {
		return;
	}
	js = d.createElement('script');
	js.id = id;
	js.async = true;
	js.src = "//connect.facebook.net/en_US/all.js";
	d.getElementsByTagName('head')[0].appendChild(js);
}(document));
